package org.jash.document.ui

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import kotlinx.coroutines.launch
import org.jash.common.log.logDebug
import org.jash.common.mvi.BaseActivity
import org.jash.common.mvi.BaseState
import org.jash.document.R
import org.jash.document.databinding.ActivityPdfBinding
import org.jash.document.model.PdfIntent
import org.jash.document.model.PdfState
import org.jash.document.model.PdfViewModel
import java.io.File

@Route(path = "/document/pdf")
class PdfActivity : BaseActivity<ActivityPdfBinding, PdfViewModel>() {
    val downDir by lazy { getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) }

    @Autowired
    @JvmField
    var url:String? = null
    @Autowired
    @JvmField
    var fileName: String? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ARouter.getInstance().inject(this)
        lifecycleScope.launch {
            viewModel.intent.send(PdfIntent.Download(url ?: "", File(downDir, fileName)))
        }
    }
    fun complete(comp:PdfState.Complete) {
        binding.pdf.fromFile(comp.path)
            .showMinimap(false)
            .enableSwipe(true)
            .load();
    }
    fun error(error:BaseState.Error) {
        logDebug(error.msg)
        Toast.makeText(this, error.msg, Toast.LENGTH_SHORT).show()
    }
}